﻿using AwesomiumDotNet;
using System;
using System.IO;
using System.Threading;

namespace BasicSample
{
    class BasicSample
    {
        int Width = 640;
        int Height = 480;
        string URL = "http://www.google.com";

        bool isRunning = true;
        WebView webView;

        public BasicSample()
        {
            WebCoreOptions options = new WebCoreOptions();
            options.LogLevel = LogLevel.None;
            WebCore webCore = new WebCore(options);

            webView = webCore.CreateWebView(Width, Height);
            webView.BeginNavigation += new EventHandler<BeginNavigationEventArgs>(OnBeginNavigation);
            webView.FinishLoading += new EventHandler<FinishLoadingEventArgs>(OnFinishLoading);
            
            webView.LoadUrl(URL);
            //webView.LoadFile("index.html");
            
            while (isRunning)
            {
                Thread.Sleep(250);
                webCore.Update();
            }
            
            System.Console.WriteLine("Done.\n");

            webView.Dispose();
            webCore.Dispose();
        }

        private void OnBeginNavigation(Object sender, BeginNavigationEventArgs e)
        {
            System.Console.WriteLine("Navigating to " + e.Url);
        }

        private void OnFinishLoading(Object sender, FinishLoadingEventArgs e)
        {
            int RowSpan = Width * 4;
            
            System.Console.WriteLine("Rendering...");

            byte[] buffer = new byte[RowSpan*Height];
            webView.Render(buffer, RowSpan, 4);

            // Write to TGA file
            FileStream fs = File.Create("result.tga");
            BinaryWriter file = new BinaryWriter(fs);
            file.Write((char)0);
            file.Write((char)0);
            file.Write((char)2);  // compressed RGBA
            file.Write((short)0);
            file.Write((short)0);
            file.Write((char)0);
            file.Write((short)0); // x origin
            file.Write((short)0); // y origin
            file.Write((short)Width);    // width
            file.Write((short)Height);   // height
            file.Write((char)32); // 32 BPP
            file.Write((char)0);

            for(int row = Height - 1; row >= 0; row--)
		        file.Write(buffer, row * RowSpan, RowSpan);

            file.Flush();
            file.Close();
            fs.Close();

            isRunning = false;
        }
    }
}
